﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace BF
{
    public static class SerializeUtil
    {
        /// <summary>
        /// 序列化
        /// </summary>
        public static byte[] SerializeToBinary(object obj, bool isEncryp = true)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, obj);

            byte[] data = stream.ToArray();
            stream.Close();
            stream.Dispose();
            if (isEncryp)
            {
                //data = AESUtil.Encrypt(data);
                for (int i = 0; i < data.Length; ++i)
                {
                    data[i] ^= 7;
                }
            }
            return data;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        public static string SerializeToString(object obj, bool isEncryp = true)
        {
            byte[] bytes = SerializeToBinary(obj, isEncryp);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        public static T Deserialize<T>(byte[] data, bool isDecryp = true)
        {
            if (isDecryp)
            {
                //data = AESUtil.Decrypt(data);
                for (int i = 0; i < data.Length; ++i)
                {
                    data[i] ^= 7;
                }
            }
            MemoryStream stream = new MemoryStream();
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(stream);

            stream.Close();
            stream.Dispose();

            return (T)obj;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        public static T Deserialize<T>(string data, bool isDecryp = true)
        {
            byte[] bytes = Convert.FromBase64String(data);
            return Deserialize<T>(bytes, isDecryp);
        }
    }
}